<template>
  <view class="viewport">
    <view class="logo">
      <image src="/static/images/logo.png"></image>
    </view>
    <view class="login">
      <view class="login-header">
        <text
          class="login-title"
          :class="{ active: loginWay === 'password' }"
          @tap="loginWay = 'password'"
          >密码登录</text
        >
        <text
          class="login-title"
          :class="{ active: loginWay === 'email' }"
          @tap="loginWay = 'email'"
          >免密登录</text
        >
      </view>
      <template v-if="loginWay === 'password'">
        <uni-forms
          :model="passwordForm"
          ref="passwordFormRef"
          :rules="passwordFormRules"
        >
          <uni-forms-item name="username">
            <uni-easyinput
              v-model="passwordForm.username"
              placeholder="请输入账号"
            ></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="password">
            <uni-easyinput
              type="password"
              v-model="passwordForm.password"
              placeholder="请输入密码"
            >
            </uni-easyinput>
          </uni-forms-item>
          <uni-forms-item>
            <view class="button-extra">
              <navigator
                url="/pages/login/forget"
                open-type="navigate"
                hover-class="navigator-hover"
                class="caption"
              >
                忘记密码
              </navigator>
              <navigator
                url="/pages/login/register"
                open-type="navigate"
                hover-class="navigator-hover"
                class="caption"
              >
                新用户注册
              </navigator>
            </view>
          </uni-forms-item>
          <button @tap="onPasswordSubmit" class="button">登录</button>
        </uni-forms>
      </template>
      <template v-else>
        <uni-forms
          :model="emailForm"
          ref="emailFormRef"
          :rules="emailFormRules"
        >
          <uni-forms-item name="email">
            <uni-easyinput
              type="text"
              v-model="emailForm.email"
              placeholder="请输入邮箱"
            ></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="code">
            <uni-easyinput
              v-model="emailForm.code"
              placeholder="请输入4位验证码"
            >
              <template #right>
                <button
                  class="code-btn"
                  :disabled="countdown > 0"
                  @tap="getEmailCaptcha()"
                >
                  {{ countdown > 0 ? countdown + "秒后重发" : "获取验证码" }}
                </button>
              </template>
            </uni-easyinput>
          </uni-forms-item>
          <uni-forms-item>
            <view class="button-extra">
              <navigator
                url="/pages/login/forget"
                open-type="navigate"
                hover-class="navigator-hover"
                class="caption"
              >
                忘记密码
              </navigator>
              <navigator
                url="/pages/login/register"
                open-type="navigate"
                hover-class="navigator-hover"
                class="caption"
              >
                新用户注册
              </navigator>
            </view>
          </uni-forms-item>
          <button @tap="onEmailSubmit" class="button">登录</button>
        </uni-forms>
      </template>
      <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
        <label class="label" @tap="isAgreePrivacy = !isAgreePrivacy">
          <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
          <text>登录/注册即视为你同意校园投票</text>
        </label>
        <navigator class="link" hover-class="none" url="./protocal"
          >《服务条款》</navigator
        >
        和
        <text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { postLoginAPI, getEmailCodeAPI, postEmailLoginAPI } from "@/api/login";
import { useUserStore } from "@/stores";
import type { userLoginType } from "@/types/login";
import { reactive, ref } from "vue";

const userStore = useUserStore();

let loginWay = ref("password");

// 传统表单登录，测试账号：13123456789 密码：123456，测试账号仅开发学习使用。
const passwordForm: userLoginType = reactive({
  username: "",
  password: "",
});

const passwordFormRef = ref<UniHelper.UniFormsInstance>();

const passwordFormRules: UniHelper.UniFormsRules = {
  username: {
    rules: [{ required: true, errorMessage: "请输入正确的账号或邮箱" }],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: "请输入密码",
      },
      {
        pattern:
          /^(?=.*[a-zA-Z])(?=.*\d|.*[!@#$%^&*()_+\-=$${};':"\\|,.<>\/?]).{8,16}$/,
        errorMessage: "密码长度为8-16位，且包含字母和数字或特殊字符",
      },
    ],
  },
};

// 表单提交
const onPasswordSubmit = async () => {
  await checkedAgreePrivacy();
  await passwordFormRef.value?.validate?.();
  const res = await postLoginAPI(passwordForm);
  userStore.token = res.data.token;
  userStore.username = res.data.username;
  await userStore.setUserInfo();
  uni.navigateBack();
};

const emailForm = reactive({
  email: "",
  code: "",
});

const emailFormRef = ref<UniHelper.UniFormsInstance>();

const emailFormRules: UniHelper.UniFormsRules = {
  email: {
    rules: [
      { required: true, errorMessage: "请输入邮箱" },
      {
        pattern:
          /^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        errorMessage: "请输入正确格式的邮箱",
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
      {
        validateFunction: function (rule, value, data, callback) {
          if (value.length !== 4) {
            callback("验证码为4位");
          }
          return true;
        },
      },
    ],
  },
};

// 表单提交
const onEmailSubmit = async () => {
  await checkedAgreePrivacy();
  await emailFormRef.value?.validate?.();
  const res = await postEmailLoginAPI(emailForm);
  userStore.token = res.data.token;
  userStore.username = res.data.username;
  await userStore.setUserInfo();
  uni.navigateBack();
};

// 请先阅读并勾选协议
const isAgreePrivacy = ref(false);
const isAgreePrivacyShakeY = ref(false);
const checkedAgreePrivacy = async () => {
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: "none",
      title: "请先阅读并勾选协议",
    });
    // 震动提示
    isAgreePrivacyShakeY.value = true;
    setTimeout(() => {
      isAgreePrivacyShakeY.value = false;
    }, 500);
    // 返回错误
    return Promise.reject(new Error("请先阅读并勾选协议"));
  }
};

const onOpenPrivacyContract = () => {
  // #ifdef MP-WEIXIN
  // 跳转至隐私协议页面
  wx.openPrivacyContract({});
  // #endif
};

let countdown = ref(0);

const setTimer = () => {
  // 设置60秒的倒计时
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 获取邮箱验证码
const getEmailCaptcha = async () => {
  await emailFormRef.value?.validateField?.("email");
  setTimer();
  await getEmailCodeAPI({
    email: emailForm.email,
    type: "login",
  });
  uni.showToast({
    icon: "none",
    title: "验证码已发送，请注意查收",
  });
};
</script>

<style lang="scss">
:deep(.uni-easyinput__content-input) {
  height: 78rpx !important;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
}

.login {
  height: 58vh;
  padding: 40rpx 20rpx 20rpx;

  .login-header {
    display: flex;
    justify-content: space-around;
    margin: 20rpx 0 30rpx;
    .login-title {
      font-size: 32rpx;
      color: #333;
    }
    .active {
      font-weight: bold;
      ::after {
        content: "";
        display: block;
        height: 2px;
        width: 80%;
        margin: 0 auto;
        background-color: #28bb9c;
        margin-top: 10rpx;
      }
    }
  }

  .input-margin {
    margin-top: 20rpx;
  }

  .code-btn {
    line-height: 78rpx;
    font-size: 28rpx;
    color: #333;
  }

  .button-extra {
    display: flex;
    justify-content: space-between;
    margin: 14rpx 2rpx 20rpx;
    .caption {
      font-size: 24rpx;
      color: #28bb9c;
    }
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 8rpx;
    color: #fff;
    background-color: #28bb9c;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;
    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;
      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;
      button {
        padding: 0;
        background-color: transparent;
        &::after {
          border: none;
        }
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }
    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

.logo {
  flex: 1;
  text-align: center;
  image {
    width: 220rpx;
    height: 220rpx;
    margin-top: 12vh;
  }
}

@keyframes animate__shakeY {
  0% {
    transform: translate(0, 0);
  }
  50% {
    transform: translate(0, -5rpx);
  }
  100% {
    transform: translate(0, 0);
  }
}

.animate__shakeY {
  animation: animate__shakeY 0.2s ease-in-out 3;
}

.button-privacy-wrap {
  position: relative;
}

.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;

  .radio {
    transform: scale(0.6);
    margin-right: -4rpx;
    margin-top: -4rpx;
    vertical-align: middle;
  }

  .link {
    display: inline;
    color: #28bb9c;
  }
}
</style>
